import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Button, Modal, Table, Input, Space, Popconfirm, message, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SaveOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios';

const ProductManage = () => {
  const [visible, setVisible] = useState(false);
  const [products, setProducts] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const openBtn = useRef(null);

  useEffect(() => {
    if (visible) {
      fetchProducts();
    }
  }, [visible]);

  const fetchProducts = useCallback(async () => {
    try {
      const response = await axios.get('/api/products');
      const { code, data: productsList, message } = response.data;
      if (code !== 0) {
        message.error('获取商品列表失败');
        return;
      }
      setProducts(productsList);
    } catch (error) {
      message.error('获取商品列表失败');
    }
  }, []);

  const showDrawer = () => {
    setVisible(true);
    setEditingId(null);
  };

  const handleAdd = async () => {
    const newProduct = {
      id: uuidv4(),
      name: '',
      image: '',
      price: 0,
      barcode: '',
      isNew: true
    };
    setProducts([newProduct, ...products]);
    setEditingId(newProduct.id);
  };

  const handleEdit = (id) => setEditingId(id);

  const handleSave = async (id) => {
    try {
      const product = products.find(p => p.id === id);
      if (product.isNew) {
        // 新增商品
        delete product.isNew;
        const response = await axios.post('/api/product/add', product);
        const { code, msg } = response.data;
        if (code !== 0) {
          message.error(msg);
          return;
        }
        message.success(msg || '添加成功');
      } else {
        // 更新商品
        const response = await axios.put(`/api/products/${id}`, product);
        const { code, msg } = response.data;
        if (code !== 0) {
          message.error(msg);
          return;
        }
        message.success(msg || '更新成功');
      }
      await fetchProducts();
      setEditingId(null);
    } catch (error) {
      console.log(error);
      message.error('操作失败');
    }
  };

  const handleDelete = async (id) => {
    if (!id) {
      message.warning('请输入条形码');
      return;
    }
    const product = products.find(p => p.id === id);
    // 添加一个基于ant design的二次确认

    try {
      const response = await axios.delete(`/api/products/${product.barcode}`);
      const { code, msg } = response.data;
      if (code !== 0) {
        message.error(msg);
        return;
      }
      message.success(msg || '删除成功');
      await fetchProducts();
    }
    catch (error) {
      message.error('删除失败');
    }

  };

  const handleChange = (id, field, value) => {
    const newProducts = products.map(item => {
      if (item.id === id) {
        return { ...item, [field]: value };
      }
      return item;
    });
    setProducts(newProducts);
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 200,
      render: (text, record) => (
        editingId === record.id ? (
          <Input value={text} onChange={(e) => handleChange(record.id, 'name', e.target.value)} />
        ) : (
          <span style={{fontSize: 16}}>{text}</span>
        )
      ),
    },
    {
      title: '图片URL',
      dataIndex: 'image',
      width: 160,
      render: (text, record) => (
        editingId === record.id ? (
          <Input value={text} onChange={(e) => handleChange(record.id, 'image', e.target.value)} />
        ) : (
          text ? (
            <Tooltip 
              title={<img src={text} style={{ maxWidth: 350, maxHeight: 350 }} />}
              overlayStyle={{ maxWidth: 'none' }}
            >
              <div>
                <img
                  src={text}
                  alt="商品图片"
                  style={{ width: 96, height: 96, objectFit: 'contain' }}
                />
              </div>
            </Tooltip>
          ) : '无图片'
        )
      ),
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 120,
      render: (text, record) => (
        editingId === record.id ? (
          <Input
            type="number"
            value={text}
            onChange={(e) => handleChange(record.id, 'price', parseFloat(e.target.value))}
          />
        ) : (
          <span style={{fontSize: 16}}>{text}</span>
        )
      ),
    },
    {
      title: '商品条码',
      dataIndex: 'barcode',
      width: 200,
      render: (text, record) => (
        editingId === record.id ? (
          <Input value={text} onChange={(e) => handleChange(record.id, 'barcode', e.target.value)} />
        ) : (
          <span style={{fontSize: 16}}>{text}</span>
        )
      ),
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          {editingId === record.id ? (
            <Button
              type="text"
              icon={<SaveOutlined />}
              onClick={() => handleSave(record.id)}
            />
          ) : (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record.id)}
            />
          )}
          <Popconfirm
            title="确定要删除这个商品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const onClose = () => {
    setVisible(false);
    if (openBtn.current) {
      openBtn.current.blur();
    }
  };

  return (
    <>
      <Button type="primary" onKeyDown={e=>e.stopPropagation()} ref={openBtn} onClick={showDrawer}>
        商品管理
      </Button>
      <Modal
        title="商品管理"
        width="80%"
        style={{ top: 60 }}
        bodyStyle={{ height: 'calc(100vh - 200px)', padding: 0 }}
        open={visible}
        onCancel={onClose}
        footer={null}
      >
        <div style={{ padding: '24px', height: '80%', overflowY: 'auto' }}>
          <div style={{ marginBottom: 16, textAlign: 'right' }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
              disabled={editingId !== null}
            >
              添加商品
            </Button>
          </div>
          <Table
            columns={columns}
            dataSource={products}
            rowKey={(record) => record.id}
            pagination={false}
          />
        </div>
      </Modal>
    </>
  );
};

export default ProductManage;
